//
//  YHFileManager.mm
//  ThunderWarriors
//
//  Created by mac on 13-3-2.
//
//

#include "YHFileManager.h"
#include "stdio.h"
#import <Foundation/Foundation.h>
#import <UIKit/UIDevice.h>

YHFileManger* YHFileManger::m_Instance = NULL;

YHFileManger* YHFileManger::sharedInstance()
{
    if (NULL == m_Instance) {
        m_Instance = new YHFileManger();
        if (m_Instance) {
            bool ret = m_Instance->init();
            if (!ret) {
                delete m_Instance;
                m_Instance = NULL;
            }
        }
    }
    return m_Instance;
}

void YHFileManger::destroyInstance()
{
    if (m_Instance) {
        m_Instance->uninit();
    }
    delete m_Instance;
    m_Instance = NULL;
}

void testFileManager()
{
    YHFileManger* fileMananger = YHFileManger::sharedInstance();
    //建立单层文件夹 OneTest
    bool ret1 = fileMananger->createDirectory("OneTest", fileMananger->getWriteablePath());
    CCLog("%s", ret1 == true ? "Success!" : "Failed!");
    //建立双层文件夹 TwoTest/Level2/
    bool ret2 = fileMananger->createDirectory("TwoTest/Level2/", fileMananger->getWriteablePath());
    CCLog("%s", ret2 == true ? "Success!" : "Failed!");
    //建立双层文件夹 TwoTest/Atlas2
    bool ret3 = fileMananger->createDirectory("TwoTest/Atlas2", fileMananger->getWriteablePath());
    CCLog("%s", ret3 == true ? "Success!" : "Failed!");
    //建立双层文件夹 ThirdTest/Atlas2
    bool ret3_2 = fileMananger->createDirectory("ThirdTest/Level2", fileMananger->getWriteablePath());
    CCLog("%s", ret3_2 == true ? "Success!" : "Failed!");
    
    //测试文件夹是否存在 UnKnown
    bool bIsDirectory;
    bool ret4 = fileMananger->fileExistsAtPath("UnKnown",fileMananger->getWriteablePath(),&bIsDirectory);
    CCLog("%s %s", ret4 == true ? "Exist!" : "Not Exist!", (ret4 && bIsDirectory) ? "IsDirectory" : "NotDirectory");
    //测试文件夹是否存在 OneTest
    bool ret5 = fileMananger->fileExistsAtPath("OneTest",fileMananger->getWriteablePath(),&bIsDirectory);
    CCLog("%s %s", ret5 == true ? "Exist!" : "Not Exist!", (ret5 && bIsDirectory) ? "IsDirectory" : "NotDirectory");
    //测试文件夹是否存在 TwoTest/Level2/
    bool ret6 = fileMananger->fileExistsAtPath("TwoTest/Level2/",fileMananger->getWriteablePath(),&bIsDirectory);
    CCLog("%s %s", ret6 == true ? "Exist!" : "Not Exist!", (ret6 && bIsDirectory) ? "IsDirectory" : "NotDirectory");
    //建立双层文件夹 TwoTest/Atlas2
    bool ret7 = fileMananger->fileExistsAtPath("TwoTest/Atlas2",fileMananger->getWriteablePath(),&bIsDirectory);
    CCLog("%s %s", ret7 == true ? "Exist!" : "Not Exist!", (ret7 && bIsDirectory) ? "IsDirectory" : "NotDirectory");
    
    //测试删除文件TwoTest/Level2/
    bool ret8 = fileMananger->removeDirectory("TwoTest/Level2/", fileMananger->getWriteablePath());
    CCLog("delete %s", ret8 ? "Success!" : "Failed");
    //测试删除文件TwoTest/Atlas2
    bool ret9= fileMananger->removeDirectory("TwoTest/Atlas2", fileMananger->getWriteablePath());
    CCLog("delete %s", ret9 ? "Success!" : "Failed");
    
    //转移文件
    std::string fromPath = fileMananger->getWriteablePath();
    fromPath = fromPath  + "ThirdTest/Level2";
    std::string toPath = fileMananger->getWriteablePath();
    toPath = toPath  + "ThirdTest/Atlas2";
    bool ret10 = fileMananger->moveItem(fromPath.c_str(), toPath.c_str());
    CCLog("move %s", ret10 ? "Success!" : "Failed");
    
    //复制文件
    std::string fromPath2 = fileMananger->getWriteablePath();
    fromPath2 = fromPath2 + "ThirdTest/Atlas2";
    std::string toPath2 = fileMananger->getWriteablePath();
    toPath2 = toPath2 + "ThirdTest/AtlasCopy";
    bool ret11 = fileMananger->copyItem(fromPath2.c_str(), toPath2.c_str());
    CCLog("copy %s", ret11 ? "Success!" : "Failed");
}

bool YHFileManger::init()
{
    setResourceDirectory(fullPathFromRelativeFile("", ""));
    
    //测试FileManager
    testFileManager();
    return true;
}

void YHFileManger::uninit()
{
    
}

YHFileManger::YHFileManger()
{
    
}

YHFileManger::~YHFileManger()
{
    
}

void YHFileManger::setResourceDirectory(const char *pszDirectoryName)
{
    CCFileUtils::sharedFileUtils()->setResourceDirectory(pszDirectoryName);
}

const char* YHFileManger::getResourceDirectory()
{
    std::string resourcePath = CCFileUtils::sharedFileUtils()->getResourceDirectory();
    return resourcePath.c_str();
}

const char* YHFileManger::getWriteablePath()
{
    std::string writePath = CCFileUtils::sharedFileUtils()->getWriteablePath();
    return writePath.c_str();
}

const char* YHFileManger::fullPathFromRelativePath(const char *pszRelativePath)
{
    if (0 == strcmp(pszRelativePath, "")) {
        return fullPathFromRelativeFile("", "");
    }
    std::string path = CCFileUtils::sharedFileUtils()->fullPathFromRelativePath(pszRelativePath);
    return path.c_str();
}

const char* YHFileManger::fullPathFromRelativeFile(const char *pszFilename, const char *pszRelativeFile)
{
    std::string path2 = CCFileUtils::sharedFileUtils()->fullPathFromRelativeFile(pszFilename, pszRelativeFile);
    return path2.c_str();
}

unsigned char* YHFileManger::getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize)
{
    return CCFileUtils::sharedFileUtils()->getFileData(pszFileName, pszMode, pSize);
}

unsigned char* YHFileManger::getFileDataFromZip(const char* pszZipFilePath, const char* pszFileName, unsigned long * pSize)
{
    return CCFileUtils::sharedFileUtils()->getFileDataFromZip(pszZipFilePath, pszFileName, pSize);
}

//创建文件夹，能够递归建立
bool YHFileManger::createDirectory(const char* newDirectory, const char* atPath)
{
    NSError* error;
    std::string strAtPath = atPath;
    if (strAtPath.size() != 0 && strAtPath[strAtPath.size()-1] != '/') {
        strAtPath.append("/");
    }
    NSString* fullPath = [NSString stringWithFormat:@"%s%s", strAtPath.c_str(), newDirectory];
    
    NSFileManager* fileManager = [NSFileManager defaultManager];
    BOOL ret = [fileManager createDirectoryAtPath:fullPath withIntermediateDirectories:YES attributes:nil error:&error];
    if (ret == NO) {
        NSLog(@"Error to create %@ withError:%@", fullPath, [error description]);
        return  false;
    }
    return true;
}

//删除文件或者文件夹
bool YHFileManger::removeDirectory(const char* fullPath)
{
    NSError* error;
    NSString* nsFullPath = [NSString stringWithFormat:@"%s", fullPath];
    BOOL ret = [[NSFileManager defaultManager] removeItemAtPath:nsFullPath error:&error];
    if (NO == ret) {
        NSLog(@"remove error: at %@ withError:%@", nsFullPath, error);
        return false;
    }
    return true;
}

//删除文件夹或者，atPath是主目录，relativePath是相对路径
bool YHFileManger::removeDirectory(const char* relativePath, const char* atPath)
{
    std::string strAtPath = atPath;
    if (strAtPath[strAtPath.size()-1] != '/') {
        strAtPath.append("/");
    }
    std::string fullPath = strAtPath + relativePath;
    return removeDirectory(fullPath.c_str());
}

bool YHFileManger::fileExistsAtPath(const char* fullPath, bool* outIsDirectory)
{
    NSString* nsFullPath = [NSString stringWithFormat:@"%s", fullPath];
    BOOL bOutIsDirectory;
    BOOL ret = [[NSFileManager defaultManager] fileExistsAtPath:nsFullPath isDirectory:&bOutIsDirectory];
    if (NO == ret) {
        return false;
    }
    else{
        if (bOutIsDirectory == YES) {
            if (outIsDirectory) {
                *outIsDirectory = true;
            }

        }
        else{
            if (outIsDirectory) {
                *outIsDirectory = false;
            }
        }
        
    }
    return true;
}

bool YHFileManger::fileExistsAtPath(const char* relativeFile, const char* atPath, bool* outIsDirectory)
{
    std::string strAtPath = atPath;
    if (strAtPath[strAtPath.size()-1] != '/') {
        strAtPath.append("/");
    }
    std::string fullPath = strAtPath + relativeFile;
    return fileExistsAtPath(fullPath.c_str(), outIsDirectory);
}

bool YHFileManger::moveItem(const char* from, const char* to)
{
    NSError* error;
    NSString* nsFrom = [NSString stringWithFormat:@"%s",from];
    NSString* nsTo = [NSString stringWithFormat:@"%s",to];
    BOOL ret = [[NSFileManager defaultManager] moveItemAtPath:nsFrom toPath:nsTo error:&error];
    if (ret == YES) {
        return true;
    }
    else{
        NSLog(@"move error:from %@ to %@ withError:%@", nsFrom, nsTo, error);
        return false;
    }
}

bool YHFileManger::renameItem(const char* path,const char* newPath)
{
    return moveItem(path, newPath);
}

//复制文件
bool YHFileManger::copyItem(const char* from, const char* to){
    NSError* error;
    NSString* nsFrom = [NSString stringWithFormat:@"%s",from];
    NSString* nsTo = [NSString stringWithFormat:@"%s",to];
    BOOL ret =[[NSFileManager defaultManager] copyItemAtPath:nsFrom toPath:nsTo error:&error];
    if (ret == YES) {
        return true;
    }
    else{
        NSLog(@"copy error:from %@ to %@ withError:%@", nsFrom, nsTo, error);
        return false;
    }
}

